package com.nd.android.u.ui.activity.recent_contact;

import ims.utils.CommUtil;
import ims.utils.IMLogUtils;

import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.common.utils.StarAppUtils;
import com.nd.android.u.business.db.dao.RecentContactRecords;
import com.nd.android.u.controller.ChatConst.LocalMessageType;
import com.nd.android.u.controller.ChatConst.MessageContentType;
import com.nd.android.u.controller.bean.contact.ForwardingParam;
import com.nd.android.u.controller.bean.contact.RecentContactItem;
import com.nd.android.u.controller.bean.event.UnreadCountChangedEvent;
import com.nd.android.u.ui.ChatEntry;
import com.nd.android.u.ui.R;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.PauseOnScrollListener;
import com.product.android.business.ApplicationVariable;

import de.greenrobot.event.EventBus;

public class RecentContactListFragment extends Fragment {

	public static String HAS_DEL_BTN_ITEM_ID = "";

	private static final String FORWARDING_PARAM = "forwarding_param";
	private static final String UPDATE_ADAPTER_AFTER_DELAY = "recent_contact_update_adapter_after_delay";
	public static final String UPDATE_RECENT_CONTACT_LIST_ADAPTER = "update_recent_contact_list_adapter";

	public static final String RECENT_CONTACT_LIST_SET_NEXT_UNREAD_ITEM = "recent_contact_list_set_next_unread_item";

	private ForwardingParam mForwardingParam;

	private int REL_SWIPE_MIN_DISTANCE;
	private int REL_SWIPE_MAX_OFF_PATH;
	private int REL_SWIPE_THRESHOLD_VELOCITY;
	private int mItemHeight;

	public static RecentContactListFragment newInstance(
			ForwardingParam forwardingParam) {
		RecentContactListFragment fragment = new RecentContactListFragment();

		Bundle args = new Bundle();
		args.putParcelable(FORWARDING_PARAM, forwardingParam);
		fragment.setArguments(args);

		return fragment;
	}

	private ScheduledExecutorService mSES;
	private ScheduledFuture<?> mSF;
	private ListView mListView;
	private RecentContactListAdapter mAdapter;

	@TargetApi(Build.VERSION_CODES.CUPCAKE)
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);


		
		mListView = (ListView) getView().findViewById(R.id.lv);

		RelativeLayout mLlHeaderView = (RelativeLayout) LayoutInflater
				.from(getActivity()).inflate(R.layout.top_search_friend_layout, null);
		
		StarAppUtils.setViewTypeFace(
				(TextView) mLlHeaderView.findViewById(R.id.tv_search), false);
		
		mLlHeaderView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				ChatEntry.INSTANCE.chatCallOtherModel_UI
						.gotoSearchUserActivity(getActivity());
			}
		});
		mListView.addHeaderView(mLlHeaderView);
		
		initOffsetFootView();
		mAdapter = new RecentContactListAdapter(getActivity(), mForwardingParam);
		mListView.setAdapter(mAdapter);
		mListView.setOnScrollListener(new PauseOnScrollListener(ImageLoader
				.getInstance(), false, true, null));

		final GestureDetector gestureDetector = new GestureDetector(
				getActivity(), new RecentContactItemGestureDetector());
		mListView.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				return gestureDetector.onTouchEvent(event);
			}
		});
	}

	/**
	 * 根据主界面底部Tab做特殊偏移处理
	 * 
	 * <br>Created 2014-8-19 下午4:04:12
	 * @author        :  HuangYK
	 */
	private void initOffsetFootView() {
		Activity activity = getActivity();
		View offsetFootView = new View(getActivity());
		int dimes = activity.getResources().getDimensionPixelSize(
				R.dimen.common_main_foot_height);
		offsetFootView.setLayoutParams(new AbsListView.LayoutParams(
				LayoutParams.MATCH_PARENT, dimes));
		mListView.addFooterView(offsetFootView);
		mListView.postInvalidate();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.recent_contact_list, container, false);
	}

	@TargetApi(Build.VERSION_CODES.DONUT)
	@Override
	public void onCreate(Bundle savedInstanceState) {
		Bundle bundle = getArguments();
		mForwardingParam = bundle.getParcelable(FORWARDING_PARAM);
		mSES = Executors.newSingleThreadScheduledExecutor();

		DisplayMetrics dm = getResources().getDisplayMetrics();
		REL_SWIPE_MIN_DISTANCE = (int) (80.0f * dm.densityDpi / 160.0f + 0.5);
		REL_SWIPE_MAX_OFF_PATH = (int) (250.0f * dm.densityDpi / 160.0f + 0.5);
		REL_SWIPE_THRESHOLD_VELOCITY = (int) (150.0f * dm.densityDpi / 160.0f + 0.5);

		super.onCreate(savedInstanceState);
	}

	@Override
	public void onDestroy() {
		mSES.shutdownNow();
		super.onDestroy();
	}

	@Override
	public void onPause() {
		EventBus eb = EventBus.getDefault();
		eb.unregister(this, String.class, UpdateTiTle.class,UnreadCountChangedEvent.class);
		eb.removeStickyEvent(String.class);
		ImageLoader.getInstance().resume();

		super.onPause();
	}

	@Override
	public void onResume() {
		updateAdapter(); // 顺序不要和下面代码对调

		EventBus eb = EventBus.getDefault();
		eb.register(this, String.class, UpdateTiTle.class,UnreadCountChangedEvent.class);
		eb.registerSticky(this, "doScroll", String.class);

		super.onResume();
	}

	// 此方法是事件的回调函数，不要删！！！
	private void doScroll(String param) {
		if (TextUtils.isEmpty(param)) {
			return;
		}
		if (param.equals(RECENT_CONTACT_LIST_SET_NEXT_UNREAD_ITEM)) {
			int firstVisiblePos = mListView.getFirstVisiblePosition();
			if (firstVisiblePos < 0) {
				return;
			}
			int lastVisiblePos = mListView.getLastVisiblePosition();
			if (lastVisiblePos < 0) {
				return;
			}
			int lastUnreadPos = mAdapter.getLastUnreadItem();
			if (lastUnreadPos < 0) {
				return;
			}

			int nextUnreadPos;
			if (lastVisiblePos >= lastUnreadPos) {
				nextUnreadPos = 0;
			} else {
				nextUnreadPos = mAdapter.getNextUnreadItem(firstVisiblePos);
				if (nextUnreadPos < 0) {
					return;
				}
				if (nextUnreadPos == Integer.MAX_VALUE) {
					nextUnreadPos = mAdapter.getNextUnreadItem(0);
					if (nextUnreadPos == Integer.MAX_VALUE) {
						nextUnreadPos = 0;
					}
				}
			}

			mListView.setSelection(nextUnreadPos);
		}
	}

	private void updateAdapter() {
		List<RecentContactItem> list = RecentContactRecords.INSTANCE.getList();
		mAdapter.setParam(list);
		mAdapter.notifyDataSetChanged();
		mListView.postInvalidate();
	}
	/**
	 * 
	 * @n<b>函数名称</b>     :updateTitle
	 * @brief                取可见的view,更新item.
	 * @see
	 * @since    Ver 1.1
	 * @param  @param fid
	 * @param  @param name
	 * @return void
	 * @<b>作者</b>          :  zhy
	 * @<b>创建时间</b>      :  2014-4-14下午5:44:45
	 */
	private void updateTitle(long fid ,String name){
		int count=mListView.getChildCount();
		for (int i=0;i<count;i++){
			View view=mListView.getChildAt(i);
			if(view instanceof RecentContactItemView){
				RecentContactItemView mview=(RecentContactItemView) view;
				int type = mview.mitem.getMessageType();
                if (type == LocalMessageType.PERSON && CommUtil.parseLong(mview.mitem.getId()) == fid) {
                    mview.initTitleByUid(name);
                }
			}else if(view instanceof RecentContactAudioItemView){
                RecentContactAudioItemView mview = (RecentContactAudioItemView) view;
                int type = mview.mitem.getMessageType();
                if (type == LocalMessageType.PERSON && CommUtil.parseLong(mview.mitem.getId()) == fid) {
                    mview.initTitleByUid(name);
                }
			}
		}
	}

	public void onEventMainThread(String param) {
		IMLogUtils.i("@@", "@@ NEW EVNETBUS EVENT: " + param.toString());
        if (param.equals(RecentContactRecordActivity.MSG_UPDATE)) {
            onRefresh();
        } else if (param.equals(UPDATE_ADAPTER_AFTER_DELAY)) {
            updateAdapter();
            mSF = null;
        } else if (param.equals(UPDATE_RECENT_CONTACT_LIST_ADAPTER)) {
            updateAdapter();
        }
	}
	
	
	
	public void onEventMainThread(UnreadCountChangedEvent event) {
		updateAdapter();
	}
	
	public void onEventMainThread(UpdateTiTle ut) {
        updateTitle(ut.mfid,ut.mname);
	}
	
	public static class UpdateTiTle {
		public long  mfid;
		public String mname;

		public UpdateTiTle(long fid, String name) {
			mfid = fid;
			mname = name;
		}
	}

	// 收到刷新通知的时候调用
	private void onRefresh() {
		if (mSF != null) {
			mSF.cancel(true);
			mSF = null;
		}
		mSF = mSES.schedule(new Runnable() {

			@Override
			public void run() {
				EventBus.getDefault().post(UPDATE_ADAPTER_AFTER_DELAY);
			}
		}, 1, TimeUnit.SECONDS);
	}

	/***** 适配器 *****/
	private static class RecentContactListAdapter extends BaseAdapter {

		private Context mCtx;
		private ForwardingParam mForwardingParam;
		private List<RecentContactItem> mList;
		private static final int TYPE_NORMARL = 0;
		private static final int TYPE_AUDIO = 1;

		public RecentContactListAdapter(Context ctx,
				ForwardingParam forwardingParam) {
			mCtx = ctx;
			mForwardingParam = forwardingParam;
		}

		private boolean isNormalUse() {
			return (mForwardingParam == null);
		}

		public int getNextUnreadItem(int basePos) {
			if ((mList == null) || mList.isEmpty()) {
				return -1;
			}

			int size = mList.size();
			for (int i = (basePos + 1); i < size; ++i) {
				RecentContactItem item = mList.get(i);
				if (item.getUnreadCount() != 0) {
					return i;
				}
			}
			return Integer.MAX_VALUE;
		}

		public int getLastUnreadItem() {
			if ((mList == null) || mList.isEmpty()) {
				return -1;
			}

			int size = mList.size();
			for (int i = (size - 1); i >= 0; --i) {
				RecentContactItem item = mList.get(i);
				if (item.getUnreadCount() != 0) {
					return i;
				}
			}
			return 0;
		}

		public void setParam(List<RecentContactItem> list) {
			mList = list;

			if (!isNormalUse()) {
				Iterator<RecentContactItem> it = mList.iterator();
				while (it.hasNext()) {
					RecentContactItem item = it.next();
					int type = item.getMessageType();
                    if ((type != LocalMessageType.PERSON) && (type != LocalMessageType.GROUP)) {
                        it.remove();
                    }
				}
			}
		}

		@Override
		public int getCount() {
			if (mList == null) {
				return 0;
			} else {
				return mList.size();
			}
		}
		
		@Override
		public int getViewTypeCount() { // 语音视图和其他item相差比较大，为了复用方便，拆成两种类型处理
			return 2;
		}
		
		@Override
        public int getItemViewType(int position) {
            RecentContactItem item = getItem(position);
            if (item.getLastMsgContentType() == MessageContentType.AUDIO
                    || item.getLastMsgContentType() == MessageContentType.OLD_AUDIO) {
                
                return TYPE_AUDIO;
            } else {
                return TYPE_NORMARL;
            }
        }

		@Override
		public RecentContactItem getItem(int position) {
			if ((position < 0) || (position > mList.size()-1)) {
				return null;
			} else {
				return mList.get(position);
			}
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
            int type = getItemViewType(position);
            RecentContactItem item = getItem(position);
            boolean showDel;
            if (TextUtils.isEmpty(RecentContactListFragment.HAS_DEL_BTN_ITEM_ID)) {
                showDel = false;
            } else if (item.getIdentity().equals(RecentContactListFragment.HAS_DEL_BTN_ITEM_ID)) {
                showDel = true;
            } else {
                showDel = false;
            }
			
			switch(type){
			case TYPE_NORMARL:{
				RecentContactItemView	view;
				if (convertView == null) {
					view = new RecentContactItemView(mCtx);
				} else {
					view = (RecentContactItemView) convertView;
				}
				view.updateContent(mCtx, item, isNormalUse(), showDel);
				view.setPosition(position);
				return view;
			}
				
			case  TYPE_AUDIO:{	
				RecentContactAudioItemView view;
				if (convertView == null) {
					view = new RecentContactAudioItemView(mCtx);
				} else {
					view = (RecentContactAudioItemView) convertView;
				}
				view.updateContent(mCtx, item, isNormalUse(), showDel);
				view.setPosition(position);
				return view;
			}
			default:
				return null;
			}
		}

	}

	private class RecentContactItemGestureDetector extends
			SimpleOnGestureListener {

		@Override
		public boolean onSingleTapUp(MotionEvent e) {
			onClick(getClickPosition(e));
			return false;
		}

		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
				float velocityY) {
			if (mItemHeight == 0) {
				if (mListView.getChildCount() > 0) {
					mItemHeight = mListView.getChildAt(0).getHeight();
				}
			}
			if (mItemHeight == 0) {
				return false;
			}
			if ((e1 != null) && (e2 != null)) {
				int maxOff;
				if (mItemHeight == 0) {
					maxOff = REL_SWIPE_MAX_OFF_PATH;
				} else {
					maxOff = mItemHeight;
				}
				if (Math.abs(e1.getY() - e2.getY()) > maxOff)
					return false;
				if (e1.getX() - e2.getX() > REL_SWIPE_MIN_DISTANCE
						&& Math.abs(velocityX) > REL_SWIPE_THRESHOLD_VELOCITY) {
					int position = getClickPosition(e1) - mListView.getHeaderViewsCount();
					right2left(position);
				} else if (e2.getX() - e1.getX() > REL_SWIPE_MIN_DISTANCE
						&& Math.abs(velocityX) > REL_SWIPE_THRESHOLD_VELOCITY) {
					int position = getClickPosition(e1) - mListView.getHeaderViewsCount();
					left2right(position);
				}
			}
			return false;
		}

		@Override
		public void onLongPress(MotionEvent e) {
			onLongClick(getClickPosition(e) - mListView.getHeaderViewsCount());
		}

		private void onClick(int position) {
			int headerCount = mListView.getHeaderViewsCount();
			position = position - headerCount;
			if (position < 0) {
				return;
			}
			if (mAdapter == null) {
				return;
			}

			RecentContactItem item = mAdapter.getItem(position);
			if (item == null) {
				return;
			}
			
            Activity activity = getActivity();
            if (isNormalUse()) {
                item.onClickItem(activity);
            } else {
                item.onForwarding(activity, mForwardingParam);
            }
		}

		private void onLongClick(int position) {
			final RecentContactItem item = getItem(position);
			if (item == null) {
				return;
			}

			AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
			builder.setItems(ApplicationVariable.INSTANCE.applicationContext
					.getResources().getStringArray(R.array.contact_opration),
					new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							if (which == 0) { // 从联系人列表中移除
								deleteItem(item);
							}
						}
					});
			builder.setNegativeButton(R.string.cancel, null);
			builder.show();
		}

		private void deleteItem(RecentContactItem item) {
			RecentContactRecords.INSTANCE.deleteItem(item);
			EventBus eb = EventBus.getDefault();
			eb.post(new UnreadCountChangedEvent());
			if (RecentContactRecords.INSTANCE.isEmpty()) {
				eb.post(RecentContactRecordActivity.RECENT_CONTACT_UPDATE_UI);
			}
		}

		private boolean isNormalUse() {
			return (mForwardingParam == null);
		}

		private RecentContactItem getItem(int position) {
			if (position < 0) {
				return null;
			}
			if (!isNormalUse()) {
				return null;
			}
			if (mAdapter == null) {
				return null;
			}
			return mAdapter.getItem(position);
		}

		private void right2left(int position) {
			RecentContactItem item = getItem(position);
			if (item == null) {
				return;
			}
			HAS_DEL_BTN_ITEM_ID = item.getIdentity();
			mAdapter.notifyDataSetChanged();

//			if (item.getUnreadCount() == 0) {
//				// 显示”删除“按钮
//				
//				HAS_DEL_BTN_ITEM_ID = item.getIdentity();
//				mAdapter.notifyDataSetChanged();
//			} else {
//				// 设为已读
//				
//				RecentContactRecords.INSTANCE.clearUnreadCount(item);
//				EventBus.getDefault().post(
//						RecentContactRecords.UNREAD_COUNT_CHANGED);
//				ToastUtils.display(R.string.already_read);
//
//				// 清除通知栏消息
//				NotificationMsg.getInstance().callbackSetNotiType();
//
//				// 向服务端确认消息
//				item.ackMsg();
//			}
		}
		
		private void left2right(int position) {
			RecentContactItem item = getItem(position);
			if (item == null) {
				return;
			}
			HAS_DEL_BTN_ITEM_ID = item.getIdentity();
			mAdapter.notifyDataSetChanged();
		}
		
		private int getClickPosition(MotionEvent e) {
			if (mListView == null) {
				return -1;
			} else {
				return mListView
						.pointToPosition((int) e.getX(), (int) e.getY());
			}
		}

	}

	/**
	 * 重新获取联系人的名称（目前只能处理群和个人)
	 * <br>Created 2014-11-8 下午2:54:25
	 * @param id 要变更名称的最近联系人
	 * @author  cb
	*/
	public void resetRecentContactName(long id){
		List<RecentContactItem> list = RecentContactRecords.INSTANCE.getList();
		String mainId=String.valueOf(id);
		for (RecentContactItem item : list) {
			if (item.getId().equals(mainId)){
				item.resetName();
				break;
			}
		}
		updateAdapter();
	}
}
